package com.brucekong.slm.controller;

import com.brucekong.slm.common.Result;
import com.brucekong.slm.model.user.UserDomain;
import com.brucekong.slm.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.brucekong.slm.config.WebSecurityConfig.SESSION_KEY;


@Controller
@Slf4j
@Api(value = "用户", tags = "用户模块")
public class MainController {

    private Result result = new Result();

    @Autowired
    private UserService userService;

    @GetMapping("/")
    @ApiIgnore()
    public String index(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(true);
        if (null != session.getAttribute(SESSION_KEY)) {
            // 登录了，就继续
            session.setAttribute(SESSION_KEY, session.getAttribute(SESSION_KEY));
            log.info("跳转到首页");
            return "index";
        }
        log.info("从/跳转到登录页面");
        return "redirect:/login";
    }


    @GetMapping("/register")
    @ApiIgnore()
    public String register() {

        log.info("跳转到注册页面");
        return "/register";
    }

    @PostMapping("/register")
    @ResponseBody
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "注册新用户", notes = "用户通过用户名和密码注册新用户", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户账号", name = "userName", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(value = "用户密码", name = "password", required = true, dataType = "string", paramType = "query")
    })
    public Result register(@RequestParam(value = "userName") String userName, @RequestParam(value = "password") String password, HttpServletRequest request) {
        log.info("register");

        userService.register(userName, password);
        UserDomain user = userService.getUserWithoutPasswordByUserName(userName);
        if (user.getUserName().equals(userName)) {
            result.setCode(0);
            result.setSuccess(true);
            result.setMsg("注册成功！");
            result.setData(user);
        } else {
            result.setCode(1);
            result.setSuccess(false);
            result.setMsg("注册失败，请重新注册");
            result.setData(null);
        }
        return result;
    }


    @GetMapping("/lostwd")
    @ApiIgnore()
    public String lostwd() {

        log.info("跳转到密码找回页面");
        return "/lostwd";
    }

    @PostMapping("/lostwd")
    @ResponseBody
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "密码找回", notes = "密码找回", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "passwd", name = "passwd", dataType = "string", paramType = "query"),
            @ApiImplicitParam(value = "password", name = "password", dataType = "string", paramType = "query")
    })
    public Result lostwd(@RequestParam(value = "passwd") String passwd, @RequestParam(value = "password") String password, HttpServletRequest request) {
        log.info("lostwd");

        // TODO 密码找回
        userService.register(passwd, password);
        result.setCode(0);
        result.setSuccess(true);
        result.setMsg("密码找回成功");
        result.setData(null);
        return result;
    }

    @GetMapping("/login")
    @ApiIgnore()
    public String login() {

        log.info("访问了/login跳转到登录页面");
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "用户登录", notes = "用户通过用户名和密码登录系统", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户账号", name = "userName", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(value = "用户密码", name = "password", required = true, dataType = "string", paramType = "query")
    })
    public Result login(@RequestParam(value = "userName") String userName, @RequestParam(value = "password") String password, HttpServletRequest request) {
        log.info("login");

        if (userName.equals("") || password.equals("")) {
            result.setCode(1);
            result.setSuccess(false);
            result.setMsg("用户或密码不能为空");
            result.setData(null);
            return result;
        }

        UserDomain user = userService.getUserByUserName(userName);
        String passwd = user.getPassword();
        String name = user.getUserName();

        if (!name.equals(userName) || !passwd.equals(password)) {
            log.info("用户不存在，或者密码错误");

            result.setCode(1);
            result.setSuccess(false);
            result.setMsg("用户不存在，或者密码错误");
            result.setData(null);
            return result;
        }
        // 设置登录session
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY, user);
        session.setMaxInactiveInterval(30 * 60); // 30分钟

        log.info("登录成功");

        UserDomain userWithoutPassword = userService.getUserWithoutPasswordByUserName(userName);
        Map<String, Object> map = new HashMap<>();
        map.put("user", userWithoutPassword);

        result.setCode(0);
        result.setSuccess(true);
        result.setMsg("登录成功");
        result.setData(map);
        return result;
    }

    @GetMapping("/logout")
    @ResponseBody
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "用户注销", notes = "用户退出系统", code = 200, produces = "application/json", responseContainer = "Map", response = Result.class)
    public Result logout(HttpServletRequest request) {
        log.info("logout");

        // 移除session
        HttpSession session = request.getSession();
        session.removeAttribute(SESSION_KEY);

        log.info("注销成功");

        Map<String, Object> map = new HashMap<>();
        map.put("isExit", true);

        result.setCode(0);
        result.setSuccess(true);
        result.setMsg("登录成功");
        result.setData(map);
        return result;
    }
}